package com.pisces.core;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 *
 *
 * @author lingxin
 * @date 2017/11/13
 */
@Before(IocInterceptor.class)
public class BaseController extends Controller {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    protected Result result = new Result();

    /**
     * 执行业务
     */
    public Result doAction(BaseCommand biz) {
        try {
            biz.initContext(this);
            try {
                biz.init();
                biz.doCommand();

            } finally {
                biz.doFinally();
            }

            result.put(biz.getData());

        } catch (BizException ex) {
            ex.printStackTrace();

            result.setSuccess(false);
            result.setCode(ex.getErrorCode());
            result.setMessage(ex.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            //logger.error(e.getMessage());

            result.setSuccess(false);
            result.setCode(Result.CODE_FAILURE);
            result.setMessage(Result.MESSAGE_UNKNOWN_EXCEPTION);
        }

        return result;
    }

    @Override
    public void renderJson() {
        Map<String, Object> renderMap = new HashMap<String, Object>();
        renderMap.put("success", result.isSuccess());
        renderMap.put("code", result.getCode());
        if (result.isSuccess()) {
            if (result.getData() != null && !result.getData().isEmpty()) {
                renderMap.put("data", result.getData());
            }

        } else {
            renderMap.put("message", result.getMessage());
        }

        renderJson(renderMap);
    }

    /**
     * 渲染页面
     */
    public void renderPage(String template) {
        if (result.isSuccess() && StrKit.notBlank(template)) {
            fillContext();
            renderFreeMarker(template);
        } else {
            setAttr("errorMessage", result.getMessage());
            setAttr("errorCode", result.getCode());
            renderErrorPage();
        }
    }

    @Override
    public void forwardAction(String actionUrl) {
        if (result.isSuccess()) {
            fillContext();
            super.forwardAction(actionUrl);

        } else {
            setAttr("errorMessage", result.getMessage());
            setAttr("errorCode", result.getCode());
            renderErrorPage();
        }
    }

    /**
     * 渲染错误页面
     */
    public void renderErrorPage() {
        renderFreeMarker("/WEB-INF/views/common/error.html");
    }


    /**
     * 填充context
     */
    private void fillContext() {
        Map<String, Object> data = result.getData();
        Set<String> keySet = data.keySet();
        for (String key : keySet) {
            setAttr(key, data.get(key));
        }
    }
}
